1290. Convert Binary Number in a Linked List to Integer
LeetCode 1290. Convert Binary Number in a Linked List to Integer
想法
這一題我們先用一變數來存放之前的值,每向前一位,就將原值向左移一位(乘以 2),並且加上新的值。
Solution
C
int getDecimalValue(struct ListNode* head) {
long long result = 0;
while (head) {
result <<= 1;
result += head->val;
head = head->next;
}
return result;
}
CPP
class Solution {
public:
int getDecimalValue(ListNode* head) {
long long result = 0;
while (head) {
result <<= 1;
result += head->val;
head = head->next;
}
return result;
}
};
JAVA
class Solution {
public int getDecimalValue(ListNode head) {
var result = 0;
while (head != null) {
result <<= 1;
result += head.val;
head = head.next;
}
return result;
}
}
JAVASCRIPT
function getDecimalValue(head) {
let result = 0;
while (head) {
result <<= 1;
result += head.val;
head = head.next;
}
return result;
}
PHP
class Solution {
/**
* @param ListNode $head
* @return Integer
*/
function getDecimalValue($head) {
$result = 0;
while ($head != null) {
$result <<= 1;
$result += $head->val;
$head = $head->next;
}
return $result;
}
}
PYTHON
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
result = 0
while head != None:
result <<= 1
result += head.val
head = head.next
return result
TYPESCRIPT
function getDecimalValue(head: ListNode | null): number {
let result = 0;
while (head !== null) {
result <<= 1;
result += head.val;
head = head.next;
}
return result;
}